import { ReactViewState, ReactView, reactControl, ReactViewControl } from "pao-aop-client";

import React from "react";
import { addon } from "pao-aop";
import './index.less';
import { Carousel, Icon, Rate, Button, InputNumber, Radio, message, Col } from "antd";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/router";
/**
 * 组件：服务套餐详情页状态
 */
export interface ServerProjectDetailsState extends ReactViewState {
  /** 数据对象 */
  productData?: any;
  /** 总价钱 */
  money?: number;
  /** 计算价钱数组 */
  moneyary?: any;
  /** 购买套餐数量 */
  count?: number;
  /** 评论列表 */
  comment?: any;
  /** 总价 */
  total_price?: any;
}

/**
 * 组件：服务套餐详情页
 */
export class ServiceProjectDetail extends ReactView<ServiceProjectDetailControl, ServerProjectDetailsState> {
  private values?: 0;
  constructor(props: any) {
    super(props);
    this.state = {
      productData: {},
      money: 0,
      moneyary: [],
      comment: [],
      total_price: 0,
    };
  }
  componentDidMount() {
    this.selectdata();
    this.setState({
      count: 1,
      total_price: this.state.productData.total_price,
    });
  }
  selectdata() {
    AppServiceUtility.service_item_serviceinfo.get_service_product_package_detail!({ id: this.props.match!.params.key }, 1, 1)!
      .then((data: any) => {
        console.warn(data);
        this.setState({ productData: data[0] }, () => {
          console.warn('this.state.productData.item_list', this.state.productData.item_list);
          if (typeof (this.state.productData.item_list) === 'object') {
            this.state.productData.item_list.forEach((item: any) => {
              this.state.moneyary.push({
                item_price: item.item_price,
                value: 0,
                key: item.item_name
              });
            });
          }
        });
      });
    AppServiceUtility.comment_manage_service.get_comment_list!({ comment_object_id: this.props.match!.params.key })!
      .then((res) => {
        this.setState({
          comment: res!.result
        });
      });
  }
  cmpprice(e: any, index: number) {
    this.state.moneyary[index].value = e.target.value;
    this.values = 0;
    this.state.moneyary.forEach((item: any) => {
      this.values = this.values + item.value;
    });
    this.setState({
      money: this.state.productData.total_price,
      count: 1
    });
  }
  numberonChange = (e: any) => {

    this.setState({ count: e }, () => {
      this.setState({ money: this.values! * e }, () => {
      });
    });
  }
  modifydata(data: any, index: number) {
    this.state.moneyary[index].key = data;
  }
  /** 加入购物车按钮 */
  add_to_cart = (e: any, isBuy: boolean) => {
    console.log(this.state, this.state.productData);
    let storage = window.localStorage;
    let dataobj = {};
    dataobj['service_product_id'] = this.props.match!.params.key;
    dataobj['item_list'] = this.state.productData.item_list;
    dataobj['count'] = this.state.count;
    dataobj['name'] = this.state.productData.name;
    dataobj['img'] = this.state.productData.picture_collection ? this.state.productData.picture_collection[0] : '';
    dataobj['is_assignable'] = this.state.productData.is_assignable;
    if (storage.getItem('shop')) {
      let shop_str = storage.getItem('shop');
      let shop_list: any = shop_str!.split('___');
      // 标识，是叠加数量还是新增
      let isAdd = true;
      let new_shop_list: any[] = [];
      shop_list.map((item: any, index: number) => {
        if (typeof (item) !== 'object') {
          item = JSON.parse(item);
        }
        if (item.service_product_id === dataobj['service_product_id']) {
          item.count += dataobj['count'];
          isAdd = false;
        }
        new_shop_list.push(JSON.stringify(item));
      });
      // 说明没有叠加数量，需要新增
      if (isAdd === true) {
        shop_list.push(JSON.stringify(dataobj!));
        new_shop_list = shop_list;
      }
      let shop = new_shop_list.join('___');
      storage.setItem('shop', shop);
      console.info(shop);
    } else {
      let shop_str = JSON.stringify(dataobj!!);
      let shop_list = [];
      shop_list.push(shop_str);
      let shop = shop_list.join('___');
      storage.setItem('shop', shop);
    }
    if (isBuy === false) {
      message.info('添加购物车成功');
    }
    console.warn(storage);
  }
  goBack = () => {
    this.props!.history!.push(ROUTE_PATH.serviceProjectindex);
  }
  productbuy = (e: any) => {
    // let status = false;
    // for (let key of this.state.moneyary) {
    //   if (key.value <= 0) {
    //     status = true;
    //   }
    // }
    // if (status) {
    //   message.error('请选择服务清单！');
    //   return;
    // }

    // let dataobj = {};
    // dataobj['service_product_id'] = this.props.match!.params.key;
    // dataobj['item_list'] = this.state.productData.item_list;
    // dataobj['count'] = this.state.count;
    // dataobj['name'] = this.state.productData.name;

    // dataobj['introduce'] = this.state.productData.introduce;
    // dataobj['total_price'] = this.state.productData.total_price * dataobj['count'];

    // console.warn(JSON.stringify(dataobj));
    this.add_to_cart(e, true);
    // this.props.history!.push(ROUTE_PATH.ServiceProjectBuy + '/' + JSON.stringify(dataobj));
    this.props.history!.push(ROUTE_PATH.ServiceProjectBuy);
  }
  shop = () => {
    this.props.history!.push(ROUTE_PATH.ServiceProjectBuy);
  }
  render() {
    return (
      <div className="product-info-ctn">
        <div className="product-details">
          <div className="product-imgs">
            <Carousel>
              {
                this.state.productData.picture_collection && this.state.productData.picture_collection.length > 0 ?
                  this.state.productData.picture_collection.map((item: any, index: number) => {
                    return (<div key={index} className="product-imgbox">
                      <img src={item} />
                    </div>);
                  }) : ''
              }
            </Carousel>
          </div>
          <div className="project-info">
            <p>{this.state.productData.name}</p>
            <span>{this.state.productData.remarks}</span>
            <div className="pricebox">
              <p>
                <span>价格：</span>
                <i>￥{this.state.productData.total_price}</i>
              </p>
            </div>
            <div className="productinfo1">
              <h5>
                {
                  this.state.productData.org_name ? this.state.productData.org_name : ''
                }
              </h5>
              <div className="score">
                <Rate character={<Icon type="heart" theme="filled" />} allowHalf={true} disabled={true} value={this.state.productData.org_level} />{this.state.productData.org_level}分
            </div>
              <p>
                {
                  this.state.productData.org_address ? this.state.productData.org_address : ''
                }
              </p>
            </div>
            <div className="productinfo2">
              <strong className="project-title">服务清单</strong>
              <ul>
                {
                  this.state.productData.item_list && this.state.productData.item_list.length > 0 ?
                    this.state.productData.item_list.map((item: any, index: number) => {
                      return (
                        <li key={index}>
                          <span className="service-name">{item.item_name}</span>
                          <Radio.Group onChange={(e) => this.cmpprice(e, index)} className="info-radio">
                            {
                              item.item_option_list && Object.keys(item.item_option_list).length > 0 ?
                                item.item_option_list.map((data: any, count: number) => {
                                  return (
                                    <Radio.Button key={count} >{data.name}：{data.option_value || 0}</Radio.Button>
                                  );
                                }) : ''
                            }
                          </Radio.Group>
                        </li>
                      );
                    }) : ''
                }
              </ul>
            </div>
            {/* <div className="productinfo3">
              <strong className="project-title">产品介绍</strong>
              <p>{this.state.productData.introduce}</p>
            </div> */}
            <div className="shopping-btn">
              <InputNumber min={1} defaultValue={1} value={this.state.count} className="shopping-ipt" onChange={this.numberonChange} />
              <Button type="primary" icon="shopping-cart" size="large" onClick={(e) => this.add_to_cart(e, false)}>
                加入购物车
              </Button>
              &nbsp;&nbsp;&nbsp;&nbsp;
              <Button type="primary" icon="shopping" size="large" onClick={this.productbuy}>
                立即购买
              </Button>
              <div className='shopping-cart' onClick={this.shop}>
                <Icon type="shopping-cart" />
              </div>
              {/* <Icon className="shopping-cart" type="" /> */}
            </div>
          </div>
        </div>
        <div className="product-comment">
          <strong>服务评价</strong>
          <ul className="comment-list">
            {
              this.state.comment.map((item: any, index: number) => {
                // console.log(item);
                return (<li key={index}>
                  <div className="user-info">
                    <div className="avtive">
                      <img src={item.comment_user_img} />
                      <span>{item.modify_date}</span>
                      <strong>{item.comment_user[0]}</strong>
                      <p>{item.content}</p>
                    </div>
                  </div>
                </li>);
              })
            }
          </ul>
        </div>
        <Col span={24} style={{ textAlign: 'center' }}>
          <Button type='ghost' name='返回' htmlType='button' onClick={this.goBack}>返回</Button>
        </Col>
      </div>
    );
  }
}

/**
 * 组件：服务套餐详情页
 * 服务套餐详情页
 */
@addon('ServiceProjectDetail', '服务套餐详情页', '描述')
@reactControl(ServiceProjectDetail, true)
export class ServiceProjectDetailControl extends ReactViewControl {
  constructor() {
    super();
  }
}
